package com.lobo.blog.controller.admin;

import com.lobo.blog.entity.User;
import com.lobo.blog.exception.UserNotFoundException;
import com.lobo.blog.service.AdminUserLoginService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * @authoer:MacieSerenity
 * @createDate: 2022/9/28
 * @description:
 */
@Controller
@RequestMapping("/admin")
public class AdminLoginController {

    @Resource
    AdminUserLoginService userLoginService;

    /**
     * 跳转到登录界面
     *
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String toLoginPage() {
        return "admin/login";
    }

    /**
     * 用户登陆
     *
     * @param username 用户名
     * @param password 密码
     * @param model    返回给前端的信息
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String Login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Model model,
                        HttpSession session
    ) {
        try {
            User user = userLoginService.findUser(username, password);
            System.out.println(user);
            user.setPassword(null);
            session.setAttribute("user", user);
        } catch (UserNotFoundException e) {
            e.printStackTrace();
            model.addAttribute("msg", "用户名或者密码错误");
            return "/admin/login";
        }
        return "/admin/adminIndex";
    }

    /**
     * 用户登出
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/logOut")
    public String userLogOut(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/admin/login";
    }
}
